package com.sgb.kjwl.view.ui.activity.home;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.bumptech.glide.Glide;

import com.sgb.capital.view.ui.activity.OpenAccountFirstActivity;
import com.sgb.capital.view.widget.MToast;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityFindingCarByMapBinding;
import com.sgb.kjwl.model.entity.map.CargoMapEntity;
import com.sgb.kjwl.model.entity.map.MapCarInfoEntity;
import com.sgb.kjwl.model.entity.self.TypeChooseEntity;
import com.sgb.kjwl.model.entity.transport.AMapAddressEntity;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.LogisticsPermissionHelper;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.PermissionCheckUtil;
import com.swgk.core.util.UserOperating;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity3;
import com.sgb.kjwl.view.ui.activity.self.logistics.InquiryActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.PublishCargoActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.activity.transport.InquireByLetterActvity;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.GeneralPrjDetailActivity;
import com.sgb.kjwl.view.widget.transport.ChooseTypePopWindow;
import com.sgb.kjwl.viewmodel.transport.MapFindingCarModel;
import com.sgb.link.router.PathTransport;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.dialog.RoundDialog;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import static com.sgb.link.router.PathTransport.MapFindingCarActivity;

/**
 * Describe:    地图找车
 * Author:  yangLei
 * Date:    2021/8/13
 */
@Route(path = MapFindingCarActivity)
public class MapFindCarActivity extends AppActivity implements AMap.OnCameraChangeListener {
    @Autowired(name = RouterKey.DATA, desc = "装货地址信息")
    public AMapAddressEntity loadingEntity;
    @Autowired(name = RouterKey.DATA1, desc = "卸货地址信息")
    public AMapAddressEntity unloadingEntity;
    @Autowired(name = RouterKey.LIST, desc = "选中的车型集合")
    public ArrayList<TypeChooseEntity> carTypeEntities;
    @Autowired(name = RouterKey.LIST1, desc = "选中的功能集合")
    public ArrayList<TypeChooseEntity> carFunctionEntities;

    private MapFindingCarModel mViewModel;
    private ActivityFindingCarByMapBinding mBinding;

    private MapView mapView;
    private AMap aMap;
    private CargoMapEntity newestEntity;
    private String searchCity = "";

    private CargoPublishEntity.LocationEntity loadAddress;
    private CargoPublishEntity.LocationEntity unloadAddress;

    //是否展开筛选条件
    private boolean isUnfold = false;
    private Bundle savedInstanceState;

    private ChooseTypePopWindow carTypePop;
    private ChooseTypePopWindow carLenPop;
    private ChooseTypePopWindow carFunctionPop;
    //选中的车长集合
    private List<TypeChooseEntity> carLenEntities = new ArrayList<>();

    private MapCarInfoEntity currCarInfo;
    private LatLng locationLatLng;

    //是否是地图点击
    private boolean mIsMarkerClick;//用于标记是否是点击marker
    private boolean isPeopleMade = false;//用于标记是否是人为滑动地图
    private boolean isFirst = true;//是否是初次进入页面的视图移动

    private String lenNos = "";
    private String typeNos = "";
    private String functionNos = "";


    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明定位回调监听器
    private AMapLocationListener mLocationListener = aMapLocation -> {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {//可在其中解析aMapLocation获取相应内容
                if (aMapLocation.getLatitude() > 0 && aMapLocation.getLongitude() > 0) {
                    mViewModel.getCarByCondition(MapFindCarActivity.this, aMapLocation.getLatitude(), aMapLocation.getLongitude(), typeNos, lenNos, functionNos);
                }
            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                MToast.showToast(getActivity(), "定位失败");
            }
        }
    };

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.savedInstanceState = savedInstanceState;
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        EventBus.getDefault().register(this);
        mViewModel = new ViewModelProvider(this).get(MapFindingCarModel.class);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_finding_car_by_map);
        mBinding.includeTitle.titleView.setText("地图找车");
        mBinding.includeTitle.ivBack.setOnClickListener(v -> finish());

        initMap();
        initPop();
        initData();
        initEvent();
    }

    private void initData() {
        inputRouterData();
        mViewModel.getCarTypeList();
        mViewModel.getCarLengthList(new ArrayList<>());
        mViewModel.getCarFunction();
    }

    /**
     * 设置页面跳转携带数据
     */
    private void inputRouterData() {
        if (loadingEntity != null) {
            AddressHelper.getInstance().findCode(loadingEntity);
            loadingAddressInfo(0, loadingEntity);
        }
        if (unloadingEntity != null) {
            AddressHelper.getInstance().findCode(unloadingEntity);
            loadingAddressInfo(1, unloadingEntity);
        }



        if (carTypeEntities == null) {
            carTypeEntities = new ArrayList<>();
        } else {
            inputCarType(carTypeEntities);
        }

        if (carFunctionEntities == null) {
            carFunctionEntities = new ArrayList<>();
        } else {
            inputCarFunction(carFunctionEntities);
        }

        if (carTypeEntities.size()>0||carFunctionEntities.size()>0){
            isUnfold = true;
            mBinding.actionTv.setText("收起筛选条件");
            mBinding.actionIv.setImageResource(R.mipmap.icon_pack_up);
            mBinding.chooseType.setVisibility(View.VISIBLE);
            mBinding.chooseLen.setVisibility(View.VISIBLE);
            mBinding.chooseFunction.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        isFirst = true;

        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        if (mapView != null) {
            mapView.onResume();
        }
        if (loadAddress == null) {
            if (mViewModel.isLocServiceEnable(this)) {//开启定位
                checkLocationPermission();
            } else {//未开启定位
                mViewModel.getCarByCondition(MapFindCarActivity.this, SharedPreferenceUtil.DEFAULT_LATITUDE, SharedPreferenceUtil.DEFAULT_LONGITUDE, typeNos, lenNos, functionNos);
            }
        } else {
            if (loadAddress.getLatitude() > 0 && loadAddress.getLongitude() > 0)
                mViewModel.getCarByCondition(MapFindCarActivity.this, loadAddress.getLatitude(), loadAddress.getLongitude(), typeNos, lenNos, functionNos);

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        if (mapView != null)
            mapView.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
            mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        if (mapView != null)
            mapView.onPause();
    }

    /**
     * 初始化触摸、点击事件
     */
    private void initEvent() {
        mBinding.includeTitle.ivBack.setOnClickListener(v -> finish());
        mBinding.setOnClick(this::onClick);
        mBinding.carInfoLay.setOnTouchListener((v, event) -> {
            mBinding.carInfoLay.setVisibility(View.GONE);
            mViewModel.resetMarkersSmall();
            return true;
        });
        mViewModel.ldCarType.observe(this, entity3s -> handleCarTypes(entity3s));
        mViewModel.ldCarLen.observe(this, entity3s -> handleCarLens(entity3s));
        mViewModel.ldCarFunction.observe(this, entity3s -> handleCarFunctions(entity3s));

        mViewModel.ldIsClickMarker.observe(this, aBoolean -> {
            if (aBoolean != null && aBoolean) {
                mIsMarkerClick = true;
            } else {
                mIsMarkerClick = false;
            }
        });
        mViewModel.ldCurrAddress.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if (integer != null) {
                    if (integer > 0 && mViewModel.getCars().size() >= integer) {
                        showCarsInfoWindow(mViewModel.getCars().get(integer - 1));
                    }
                }
            }
        });
        mViewModel.ldSearchResult.observe(this, integer -> {
            mBinding.mapView.setVisibility(View.VISIBLE);
            if (integer != null) {
                MToast.showToast(this, String.format("当前城市共搜索到%d条信息", integer));
                if (integer == 0) {
                    mBinding.carInfoLay.setVisibility(View.GONE);
                }
            } else {
                MToast.showToast(this, "搜索出错");
            }
        });

        mViewModel.pLd.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                gotoEnquiry();
            }
        });

        mViewModel.ldAddChangeListener.observe(this, aBoolean -> {
            if (aBoolean != null & aBoolean) {
                aMap.setOnCameraChangeListener(MapFindCarActivity.this);
            } else {
                aMap.setOnCameraChangeListener(null);
            }
        });

        mViewModel.ldInquiry.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    if (currCarInfo != null)
                        InquiryActivity.startCarInquiry(MapFindCarActivity.this, currCarInfo.getNo(), currCarInfo.getTelphone());
                } else {
                    MToast.showToast(MapFindCarActivity.this, "不能对自己发布的车辆进行询价！");
                }
            }
        });
    }

    private void initPop() {
        carTypePop = new ChooseTypePopWindow(this, "选择车型");
        carTypePop.setOnDismissListener(() -> mBinding.popBg.setVisibility(View.GONE));
        carTypePop.setOnResultClick((key1, key2, key3) -> {
            List<TypeChooseEntity> entity = (List<TypeChooseEntity>) key1;
            if (entity == null)
                return;
            carTypeEntities.clear();
            carTypeEntities.addAll(entity);
            inputCarType(carTypeEntities);
        });
        carLenPop = new ChooseTypePopWindow(this, "选择车长");
        carLenPop.setOnDismissListener(() -> mBinding.popBg.setVisibility(View.GONE));
        carLenPop.setOnResultClick((key1, key2, key3) -> {
            List<TypeChooseEntity> entity = (List<TypeChooseEntity>) key1;
            inputCarLen(entity);
        });

        carFunctionPop = new ChooseTypePopWindow(this, "选择车辆功能");
        carFunctionPop.setOnDismissListener(() -> mBinding.popBg.setVisibility(View.GONE));
        carFunctionPop.setOnResultClick((key1, key2, key3) -> {
            List<TypeChooseEntity> entity = (List<TypeChooseEntity>) key1;
            if (entity == null)
                return;
            carFunctionEntities.clear();
            carFunctionEntities.addAll(entity);
            inputCarFunction(carFunctionEntities);
        });
    }

    private void gotoEnquiry() {
        if (UserOperating.getInstance().isNotOpenFundAccount(this, PermissionCheckUtil.KEY_WODEXUNJIA)) {
            return;
        }
        mViewModel.getInquiryPermissions(currCarInfo.getNo());
    }

    /**
     * 在地图上展示车源信息弹窗
     *
     * @param info 车源信息
     */
    private void showCarsInfoWindow(MapCarInfoEntity info) {
        if (info == null)
            return;
        currCarInfo = info;
        if (!TextUtils.isEmpty(info.getName())) {
            mBinding.ownerName.setText(info.getName());
        }
        if (!TextUtils.isEmpty(info.getCarNumber())) {
            mBinding.carNum.setText(info.getCarNumber());
        }

        String carInfo = "";
        if (!TextUtils.isEmpty(info.getCarTypeName())) {
            carInfo = info.getCarTypeName() + "/";
        }
        if (!TextUtils.isEmpty(info.getCarLenName())) {
            carInfo += info.getCarLenName() + "/";
        }
        if (info.getWeight() != null) {
            carInfo += NumberUtil.trim0(info.getWeight()) + "吨/";
        }
        if (!TextUtils.isEmpty(info.getFunctionNos())) {
            carInfo += info.getFunctionNos() + "/";
        }
        if (!TextUtils.isEmpty(carInfo)) {
            carInfo = carInfo.substring(0, carInfo.length() - 1);
            mBinding.carInfo.setText(carInfo);
        } else {
            mBinding.carInfo.setText("");
        }

        if (!TextUtils.isEmpty(currCarInfo.getCarImage())) {
            Glide.with(this)
                    .load(currCarInfo.getCarImage())
                    .placeholder(R.drawable.default_car)
                    .error(R.drawable.default_car)
                    .into(mBinding.ivCar);
        }

        mBinding.carInfoLay.setVisibility(View.VISIBLE);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void acceptEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CARGO_RELEASE_SUCCESS_MAP_DATA) {
            if (event.getMessageData() != null) {
                CargoMapEntity mapEntity = (CargoMapEntity) event.getMessageData();
                inputSourceInfo(mapEntity);
            }
        }
    }

    /**
     * 输入货源信息
     *
     * @param mapEntity
     */
    private void inputSourceInfo(CargoMapEntity mapEntity) {
        if (mapEntity == null)
            return;
        newestEntity = mapEntity;
        if (mapEntity.getCarTypeList() != null && mapEntity.getCarTypeList().size() > 0) {
            List<TypeChooseEntity> chooseEntities = new ArrayList<>();
            for (GoodsInfoTypeEntity3 entity3 : mapEntity.getCarTypeList()) {
                if (!TextUtils.isEmpty(entity3.getNo()) && !TextUtils.isEmpty(entity3.getName())) {
                    TypeChooseEntity chooseEntity = new TypeChooseEntity();
                    chooseEntity.setSelect(true);
                    chooseEntity.setName(entity3.getName());
                    chooseEntity.setNo(entity3.getNo());
                    chooseEntities.add(chooseEntity);
                    for (TypeChooseEntity typeChooseEntity : carTypePop.getMList()) {
                        if (entity3.getNo().equals(typeChooseEntity.getNo()))
                            typeChooseEntity.setSelect(true);
                    }
                }
            }
            carTypeEntities.clear();
            carTypeEntities.addAll(chooseEntities);
            inputCarType(carTypeEntities);
            carTypePop.getMAdapter().notifyDataSetChanged();
        } else {
            mBinding.carType.setText("请选择车型");
            typeNos = "";
            mBinding.carType.setTextColor(Color.parseColor("#C0C4CC"));
        }

        if (mapEntity.getCarLenList() != null && mapEntity.getCarLenList().size() > 0) {
            List<TypeChooseEntity> chooseEntities = new ArrayList<>();
            for (GoodsInfoTypeEntity3 entity3 : mapEntity.getCarLenList()) {
                if (!TextUtils.isEmpty(entity3.getNo()) && !TextUtils.isEmpty(entity3.getName())) {
                    TypeChooseEntity chooseEntity = new TypeChooseEntity();
                    chooseEntity.setSelect(true);
                    chooseEntity.setName(entity3.getName());
                    chooseEntity.setNo(entity3.getNo());
                    chooseEntities.add(chooseEntity);

                    for (TypeChooseEntity typeChooseEntity : carLenPop.getMList()) {
                        if (entity3.getNo().equals(typeChooseEntity.getNo()))
                            typeChooseEntity.setSelect(true);
                    }
                }
            }
            inputCarLen(chooseEntities);
            carLenPop.getMAdapter().notifyDataSetChanged();
        } else {
            mBinding.carLen.setText("请选择车长");
            lenNos = "";
            mBinding.carLen.setTextColor(Color.parseColor("#C0C4CC"));
        }
        //显示更多筛选条件
        mBinding.chooseType.setVisibility(View.VISIBLE);
        mBinding.chooseLen.setVisibility(View.VISIBLE);
        mBinding.chooseFunction.setVisibility(View.VISIBLE);
        mBinding.actionTv.setText("收起筛选条件");
        mBinding.actionIv.setImageResource(R.mipmap.icon_pack_up);

        StringBuilder addressInfo = new StringBuilder();
        if (mapEntity.getSendLocation() != null) {
            loadAddress = mapEntity.getSendLocation();
            if (!TextUtils.isEmpty(loadAddress.getCity())) {
                addressInfo.append(loadAddress.getCity().replace("市", ""));
            }
            if (!TextUtils.isEmpty(loadAddress.getDistrict())) {
                addressInfo.append(loadAddress.getDistrict().replace("区", ""));
            }

            if (!TextUtils.isEmpty(loadAddress.getAddress())) {
                mBinding.loadPlaceEdit.setText(loadAddress.getAddress());
            } else {
                mBinding.loadPlaceEdit.setText("");
            }
            if (loadAddress.getLatitude() > 0 && loadAddress.getLongitude() > 0) {
                mViewModel.getCarByCondition(MapFindCarActivity.this, loadAddress.getLatitude(), loadAddress.getLongitude(), typeNos, lenNos, functionNos);
            }
        } else {
            loadAddress = null;
        }

        addressInfo.append(" → ");

        if (mapEntity.getDestLocation() != null) {
            unloadAddress = mapEntity.getDestLocation();
            if (!TextUtils.isEmpty(unloadAddress.getCity())) {
                addressInfo.append(unloadAddress.getCity().replace("市", ""));
            }
            if (!TextUtils.isEmpty(unloadAddress.getDistrict())) {
                addressInfo.append(unloadAddress.getDistrict().replace("区", ""));
            }
            if (!TextUtils.isEmpty(unloadAddress.getAddress())) {
                mBinding.unloadPlaceEdit.setText(unloadAddress.getAddress());
                mBinding.endClean.setVisibility(View.VISIBLE);
            } else {
                mBinding.unloadPlaceEdit.setText("");
                mBinding.endClean.setVisibility(View.GONE);
            }
        } else {
            setDestinationAddressEmpty();
        }

        mBinding.newestSourceInfo.setText(addressInfo.toString().trim());
        mBinding.newestSourceLay.setVisibility(View.VISIBLE);
    }

    /**
     * 处理车长数据
     *
     * @param entities
     */
    private void handleCarLens(List<GoodsInfoTypeEntity3> entities) {
        if (entities != null && entities.size() > 0) {
            List<TypeChooseEntity> chooseEntities = new ArrayList<>();
            for (GoodsInfoTypeEntity3 entity : entities) {
                TypeChooseEntity entity1 = new TypeChooseEntity();
                entity1.setSelect(false);
                entity1.setName(entity.getName());
                entity1.setNo(entity.getNo());
                if (carLenEntities.size() > 0) {
                    for (TypeChooseEntity en : carLenEntities) {
                        if (entity.getNo().equals(en.getNo())) {
                            entity1.setSelect(true);
                        }
                    }
                }
                chooseEntities.add(entity1);
            }
            carLenPop.setData(chooseEntities);
        }
    }

    /**
     * 处理车型数据
     *
     * @param entities
     */
    private void handleCarTypes(List<GoodsInfoTypeEntity3> entities) {
        if (entities != null && entities.size() > 0) {
            List<TypeChooseEntity> chooseEntities = new ArrayList<>();
            for (GoodsInfoTypeEntity3 entity : entities) {
                TypeChooseEntity entity1 = new TypeChooseEntity();
                entity1.setSelect(false);
                entity1.setName(entity.getName());
                entity1.setNo(entity.getNo());
                if (carTypeEntities.size() > 0) {
                    for (TypeChooseEntity en : carTypeEntities) {
                        if (entity.getNo().equals(en.getNo())) {
                            entity1.setSelect(true);
                        }
                    }
                }
                chooseEntities.add(entity1);
            }
            carTypePop.setData(chooseEntities);
        }
    }

    /**
     * 处理车辆功能数据
     *
     * @param entities
     */
    private void handleCarFunctions(List<GoodsInfoTypeEntity3> entities) {
        if (entities != null && entities.size() > 0) {
            List<TypeChooseEntity> chooseEntities = new ArrayList<>();
            for (GoodsInfoTypeEntity3 entity : entities) {
                TypeChooseEntity entity1 = new TypeChooseEntity();
                entity1.setSelect(false);
                entity1.setName(entity.getName());
                entity1.setNo(entity.getNo());
                if (carFunctionEntities.size() > 0) {
                    for (TypeChooseEntity en : carFunctionEntities) {
                        if (entity.getNo().equals(en.getNo())) {
                            entity1.setSelect(true);
                        }
                    }
                }
                chooseEntities.add(entity1);
            }
            carFunctionPop.setData(chooseEntities);
        }
    }

    /**
     * 录入车型
     *
     * @param entity
     */
    private void inputCarType(List<TypeChooseEntity> entity) {
        inputCarLen(new ArrayList<>());
        carLenPop.cleanSelector(false);
        typeNos = "";
        lenNos = "";

        List<String> strings = new ArrayList<>();
        String carTypeStr = "";
        for (TypeChooseEntity typeEntity : carTypeEntities) {
            if (!TextUtils.isEmpty(typeEntity.getName())) {
                carTypeStr = carTypeStr + typeEntity.getName() + "/";
            }
            if (!TextUtils.isEmpty(typeEntity.getNo())) {
                strings.add(typeEntity.getNo());
                typeNos += typeEntity.getNo() + ",";
            }
        }
        if (typeNos.length() > 0) {
            typeNos = typeNos.substring(0, typeNos.length() - 1);
        }

        if (carTypeStr.length() > 0) {
            carTypeStr = carTypeStr.substring(0, carTypeStr.length() - 1);
        }

        if (TextUtils.isEmpty(carTypeStr)) {
            mBinding.carType.setText("请选择车型");
            mBinding.carType.setTextColor(Color.parseColor("#C0C4CC"));
        } else {
            mBinding.carType.setText(carTypeStr.trim());
            mBinding.carType.setTextColor(Color.parseColor("#333333"));
        }

        mViewModel.getCarLengthList(strings);
    }

    /**
     * 录入车长
     *
     * @param entity
     */
    private void inputCarLen(List<TypeChooseEntity> entity) {
        if (entity == null)
            return;
        carLenEntities.clear();
        carLenEntities.addAll(entity);
        lenNos = "";

        String carTypeStr = "";
        if (entity.size() > 0) {
            for (TypeChooseEntity typeEntity : carLenEntities) {
                if (!TextUtils.isEmpty(typeEntity.getName())) {
                    carTypeStr = carTypeStr + typeEntity.getName() + "/";
                }
                if (!TextUtils.isEmpty(typeEntity.getNo())) {
                    lenNos += typeEntity.getNo() + ",";
                }
            }
        }
        if (!TextUtils.isEmpty(lenNos)) {
            lenNos = lenNos.substring(0, lenNos.length() - 1);
        }
        if (!TextUtils.isEmpty(carTypeStr)) {
            carTypeStr = carTypeStr.substring(0, carTypeStr.length() - 1);
        }

        if (TextUtils.isEmpty(carTypeStr)) {
            mBinding.carLen.setText("请选择车长");
            mBinding.carLen.setTextColor(Color.parseColor("#C0C4CC"));
        } else {
            mBinding.carLen.setText(carTypeStr.trim());
            mBinding.carLen.setTextColor(Color.parseColor("#333333"));
        }
    }

    /**
     * 录入车辆功能
     *
     * @param entity
     */
    private void inputCarFunction(List<TypeChooseEntity> entity) {
        functionNos = "";
        String carFunStr = "";
        if (entity.size() > 0) {
            for (TypeChooseEntity typeEntity : carFunctionEntities) {
                if (!TextUtils.isEmpty(typeEntity.getName())) {
                    carFunStr = carFunStr + typeEntity.getName() + "/";
                }
                if (!TextUtils.isEmpty(typeEntity.getNo())) {
                    functionNos += typeEntity.getNo() + ",";
                }
            }
        }
        if (!TextUtils.isEmpty(functionNos)) {
            functionNos = functionNos.substring(0, functionNos.length() - 1);
        }
        if (!TextUtils.isEmpty(carFunStr)) {
            carFunStr = carFunStr.substring(0, carFunStr.length() - 1);
        }

        if (TextUtils.isEmpty(carFunStr)) {
            mBinding.carFunction.setText("请选择车辆功能");
            mBinding.carFunction.setTextColor(Color.parseColor("#C0C4CC"));
        } else {
            mBinding.carFunction.setText(carFunStr.trim());
            mBinding.carFunction.setTextColor(Color.parseColor("#333333"));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == 201 && resultCode == 200) {
                int type = data.getIntExtra(RouterKey.INT, 0);
                AMapAddressEntity entity = data.getParcelableExtra(RouterKey.DATA);
                if (entity != null) {
                    loadingAddressInfo(type, entity);
                }
            }
        }
    }

    /**
     * 设置地址信息
     *
     * @param type   地址类型（起点、终点）
     * @param entity 地址信息数据
     */
    private void loadingAddressInfo(int type, AMapAddressEntity entity) {
        AddressHelper.getInstance().findCode(entity);
        CargoPublishEntity.LocationEntity locationEntity = new CargoPublishEntity.LocationEntity();
        locationEntity.setProvince(entity.getProvince());
        locationEntity.setProvinceNo(entity.getProvinceNo());
        locationEntity.setCity(entity.getCity());
        locationEntity.setCityNo(entity.getCityNo());
        locationEntity.setDistrict(entity.getDistrict());
        locationEntity.setDistrictNo(entity.getDistrictNo());
        locationEntity.setLatitude(entity.getLatitude());
        locationEntity.setLongitude(entity.getLongitude());
        locationEntity.setAddress(entity.getStreet() + entity.getSnippet());
        if (!TextUtils.isEmpty(entity.getCity()))
            searchCity = entity.getCity().replace("市", "");
        if (type == 0) {
            loadAddress = locationEntity;
            if (!TextUtils.isEmpty(loadAddress.getAddress())) {
                mBinding.loadPlaceEdit.setText(loadAddress.getAddress());
            }
            mBinding.carInfoLay.setVisibility(View.GONE);
        } else if (type == 1) {
            unloadAddress = locationEntity;
            if (!TextUtils.isEmpty(unloadAddress.getAddress())) {
                mBinding.unloadPlaceEdit.setText(unloadAddress.getAddress());
                mBinding.endClean.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.pop_bg:
                mBinding.popBg.setVisibility(View.GONE);
                break;

            case R.id.window_layout:
            case R.id.car_info_inner_lay:
                break;

            case R.id.invite_lay:
                if (!UserOperating.getInstance().isLogged()) {
                    VerificationCodeLoginActivity.start(this);
                } else if (currCarInfo != null && !TextUtils.isEmpty(currCarInfo.getUserNo())) {
                    LogisticsPermissionHelper.getInstance().checkPermissionToInvite(this, currCarInfo.getUserNo(), 0);
                }
                break;

            case R.id.end_clean:
                setDestinationAddressEmpty();
                break;

            case R.id.action_layout:
                if (isUnfold) {//收起
                    isUnfold = false;
                    mBinding.actionTv.setText("更多筛选条件");
                    mBinding.actionIv.setImageResource(R.mipmap.icon_pack_down);
                    mBinding.chooseType.setVisibility(View.GONE);
                    mBinding.chooseLen.setVisibility(View.GONE);
                    mBinding.chooseFunction.setVisibility(View.GONE);
                } else {//展开
                    isUnfold = true;
                    mBinding.actionTv.setText("收起筛选条件");
                    mBinding.actionIv.setImageResource(R.mipmap.icon_pack_up);
                    mBinding.chooseType.setVisibility(View.VISIBLE);
                    mBinding.chooseLen.setVisibility(View.VISIBLE);
                    mBinding.chooseFunction.setVisibility(View.VISIBLE);
                }
                break;

            case R.id.choose_type:
                carTypePop.showDownPopwindow(mBinding.chooseType, false);
                carTypePop.setTittle("选择车型");
                carTypePop.setLeftBtnStr("重置");
                mBinding.popBg.setVisibility(View.VISIBLE);
                break;

            case R.id.choose_len:
                carLenPop.showDownPopwindow(mBinding.chooseLen, false);
                carLenPop.setTittle("选择车长");
                carLenPop.setLeftBtnStr("重置");
                mBinding.popBg.setVisibility(View.VISIBLE);
                break;

            case R.id.choose_function:
                carFunctionPop.showDownPopwindow(mBinding.chooseFunction, false);
                carFunctionPop.setTittle("选择车辆功能");
                carFunctionPop.setLeftBtnStr("重置");
                carFunctionPop.setSingle(true);
                mBinding.popBg.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onMultiClick(View v) {
        switch (v.getId()) {
            case R.id.letter_lay://函询
                if (!UserOperating.getInstance().isLogged()) {
                    VerificationCodeLoginActivity.start(this);
                } else if (currCarInfo != null) {
                    InquireByLetterActvity.start(this, 2, currCarInfo.getName(), currCarInfo.getUserNo(), currCarInfo.getNo(), currCarInfo.getCarNumber());
                }
                break;

            case R.id.enquiry_btn://车辆询价
                if (!UserOperating.getInstance().isLogged()) {
                    VerificationCodeLoginActivity.start(this);
                    return;
                }
                mViewModel.getLogisticsPermission(MapFindCarActivity.this);
                break;

            case R.id.im_lay:
                if (!UserOperating.getInstance().isLogged()) {
                    VerificationCodeLoginActivity.start(this);
                }
                if (!TextUtils.isEmpty(currCarInfo.getDriverCreateIm())) {
                    IMUtils.getInstance().buildSingleTalking(currCarInfo.getDriverCreateIm());
                }
                break;

            case R.id.newest_source_lay:
                if (newestEntity != null && !TextUtils.isEmpty(newestEntity.getNo())) {
                    GeneralPrjDetailActivity.start(this, newestEntity.getNo(), 0, false);//普通货源
                }
                break;

            case R.id.call_lay:
                if (!UserOperating.getInstance().isLogged()) {
                    VerificationCodeLoginActivity.start(this);
                } else if (currCarInfo != null && !TextUtils.isEmpty(currCarInfo.getTelphone())) {
                    new RoundDialog.Builder(this)
                            .title("确认呼叫")
                            .content(currCarInfo.getTelphone())
                            .confirm("确定")
                            .cancel("取消")
                            .cancelable(false)
                            .confirmCallback(on -> {
                                Intent intent = new Intent(Intent.ACTION_DIAL);
                                Uri data = Uri.parse("tel:" + currCarInfo.getTelphone());
                                intent.setData(data);
                                startActivity(intent);
                            }).show();
                }
                break;

            case R.id.load_place_edit:
                ARouter.getInstance().build(PathTransport.AddressSelectionActivity)
                        .withString(RouterKey.STRING, searchCity)
                        .withInt(RouterKey.INT, 0)
                        .navigation(this, 201);
                break;

            case R.id.unload_place_edit:
                ARouter.getInstance().build(PathTransport.AddressSelectionActivity)
                        .withString(RouterKey.STRING, searchCity)
                        .withInt(RouterKey.INT, 1)
                        .navigation(this, 201);
                break;

            case R.id.published_sources:
                //未登录前往登录页面
                if (!UserOperating.getInstance().isLogged()) {
                    VerificationCodeLoginActivity.start(this);
                } else {
                    boolean personAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
                    int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
                    pushGoodsInfo(personAuth, type);
                }
                break;

            case R.id.search_vehicles:
                if (loadAddress != null && loadAddress.getLongitude() > 0 && loadAddress.getLatitude() > 0) {
                    mBinding.carInfoLay.setVisibility(View.GONE);
                    isPeopleMade = true;
                    mViewModel.getCarByCondition(MapFindCarActivity.this, loadAddress.getLatitude(), loadAddress.getLongitude(), typeNos, lenNos, functionNos);
                } else {
                    MToast.showToast(this, "请选择装货地址");
                }
                break;
        }
    }

    /**
     * 设置卸货地信息为空
     */
    private void setDestinationAddressEmpty() {
        mBinding.endClean.setVisibility(View.GONE);
        mBinding.unloadPlaceEdit.setText("");
        unloadAddress = null;
    }

    /**
     * 验证用户信息并发布货源
     *
     * @param personAuth
     * @param type       0个人 1企业 2团队
     */
    private void pushGoodsInfo(boolean personAuth, int type) {
        if (personAuth) {
            if (UserOperating.getInstance().getUserInfo() == null) {
                return;
            }
            if (type == 0) {
                if (!UserOperating.getInstance().getUserInfo().isDriverOpenFundsAccount()) {
                    new RoundDialog.Builder(this)
                            .title("提示")
                            .content("开通在线收款账户后\n可使用此功能")
                            .cancel("知道了")
                            .confirm("前往开户")
                            .contentGravity(Gravity.CENTER)
                            .cancelable(false)
                            .confirmCallback(v -> {
                                OpenAccountFirstActivity.start(this, true);
                            })
                            .show();
                    return;
                }
                publishCargoSkip();
            } else if (type == 2) {//当前团队
                if (!UserOperating.getInstance().getUserInfo().isDriverOpenFundsAccount()) {
                    new RoundDialog.Builder(this)
                            .title("提示")
                            .content("开通在线收款账户后\n可使用此功能")
                            .cancel("知道了")
                            .confirm("前往开户")
                            .contentGravity(Gravity.CENTER)
                            .cancelable(false)
                            .confirmCallback(v -> {
                                OpenAccountFirstActivity.start(this, true);
                            })
                            .show();
                    return;
                }
                publishCargoSkip();
            } else {//当前企业
                if (!UserOperating.getInstance().getUserInfo().isOpenFundsAccount()) {
                    new RoundDialog.Builder(this)
                            .title("提示")
                            .content("开通在线收款账户后\n可使用此功能")
                            .cancel("知道了")
                            .confirm("前往开户")
                            .contentGravity(Gravity.CENTER)
                            .cancelable(false)
                            .confirmCallback(v -> {
                                OpenAccountFirstActivity.start(this, false);
                            })
                            .show();
                    return;
                }
                if (UserOperating.getInstance().hasCompanyPermission(PermissionCheckUtil.KEY_HUOYUANGUANLI)) {//个人加入企业有权限
                    publishCargoSkip();
                } else {
                    new RoundDialog.Builder(this)
                            .title("提示")
                            .content(UserOperating.getInstance().getTeamOrCompanyName() + "未授予您发布货源的权限。建议您联系管理员分配权限")
                            .singleBtn(true)
                            .confirm("我知道了")
                            .contentGravity(Gravity.CENTER)
                            .cancelable(false)
                            .show();
                }
            }
        } else {//去实名认证
            new RoundDialog.Builder(this)
                    .title("提示")
                    .content("您当前未实名认证，是否立即认证？")
                    .cancel("取消")
                    .confirm("确定")
                    .contentGravity(Gravity.CENTER)
                    .cancelable(false)
                    .confirmCallback(v -> {
                        AuthActivity3.start(MapFindCarActivity.this);
                    })
                    .show();
        }
    }

    /**
     * 根据搜索条件取发布货源
     */
    private void publishCargoSkip() {
        CargoMapEntity cargoMapEntity = new CargoMapEntity();
        if (carLenEntities != null && carLenEntities.size() > 0) {
            List<GoodsInfoTypeEntity3> lenList = new ArrayList<>();
            for (TypeChooseEntity carLenEntity : carLenEntities) {
                if (!TextUtils.isEmpty(carLenEntity.getName()) && !TextUtils.isEmpty(carLenEntity.getNo())) {
                    GoodsInfoTypeEntity3 lenEntity = new GoodsInfoTypeEntity3(carLenEntity.getNo(), carLenEntity.getName());
                    lenList.add(lenEntity);
                }
            }
            cargoMapEntity.setCarLenList(lenList);
        }

        if (carTypeEntities != null && carTypeEntities.size() > 0) {
            List<GoodsInfoTypeEntity3> typeList = new ArrayList<>();
            for (TypeChooseEntity carTypeEntity : carTypeEntities) {
                if (!TextUtils.isEmpty(carTypeEntity.getName()) && !TextUtils.isEmpty(carTypeEntity.getNo())) {
                    GoodsInfoTypeEntity3 typeEntity = new GoodsInfoTypeEntity3(carTypeEntity.getNo(), carTypeEntity.getName());
                    typeList.add(typeEntity);
                }
            }
            cargoMapEntity.setCarTypeList(typeList);
        }

        //装卸地
        if (loadAddress != null)
            cargoMapEntity.setSendLocation(loadAddress);
        if (unloadAddress != null)
            cargoMapEntity.setDestLocation(unloadAddress);
        PublishCargoActivity.start(this, cargoMapEntity);
    }

    /**
     * 初始化地图（高德3D地图）
     */
    private void initMap() {
        mapView = mBinding.mapView;
        mapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        mViewModel.setAMap(aMap);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(mViewModel.zoomLevel));//缩放比例
        /**
         * 设置一些aMap的属性
         */
//        aMap.setMapTextZIndex(2);//地图文字的Z轴指数,设置为2可以将地图底图文字设置在添加的覆盖物之上
        UiSettings uiSettings = aMap.getUiSettings();//地图的UI设置控制器
        uiSettings.setZoomControlsEnabled(true);//是否可以缩放
        uiSettings.setCompassEnabled(false);// 设置指南针是否显示
        uiSettings.setZoomControlsEnabled(false);// 设置缩放按钮是否显示
        uiSettings.setScaleControlsEnabled(true);// 设置比例尺是否显示
        uiSettings.setRotateGesturesEnabled(true);// 设置地图旋转是否可用
        uiSettings.setTiltGesturesEnabled(true);// 设置地图倾斜是否可用
        uiSettings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setOnCameraChangeListener(this);
        initLocation();
    }

    /**
     * 初始化定位服务信息
     */
    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
    }

    /**
     * 检查是否有定位权限
     */
    private void checkLocationPermission() {
        EsayPermissions.with(this)
                .permission(Manifest.permission.ACCESS_FINE_LOCATION)
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        //有定位权限，中心点显示为当前定位
                        if (mLocationClient != null) {
                            mLocationClient.startLocation();
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        //没有定位权限，中心点显示为乌鲁木齐
                        mViewModel.getCarByCondition(MapFindCarActivity.this, SharedPreferenceUtil.DEFAULT_LATITUDE, SharedPreferenceUtil.DEFAULT_LONGITUDE, typeNos, lenNos, functionNos);
                    }
                });
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        if (isFirst) {
            isFirst = false;
            return;
        }
        MLog.d("deBug", "滑动结束，isPeopleMade=" + isPeopleMade + ",mIsMarkerClick=" + mIsMarkerClick);
        if (!isPeopleMade) {
            if (!mIsMarkerClick) {
                if (mViewModel.zoomLevel != cameraPosition.zoom) {
                    //地图缩放，不做数据搜索操作
                    mViewModel.zoomLevel = cameraPosition.zoom;
                    MLog.d("deBug", "滑动结束，缩放");
                } else {
                    locationLatLng = cameraPosition.target;
                    mViewModel.getCarByCondition(MapFindCarActivity.this, locationLatLng.latitude, locationLatLng.longitude, typeNos, lenNos, functionNos);
                }

            } else {
                mIsMarkerClick = false;
            }
        } else {
            isPeopleMade = false;
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }
}
